package com.cliang.tools.db;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

/**
 * 数据库连接类
 */
public class DB {
    private static String driverClass=null;
    private static String jdbcUrl=null;
    private static String user=null;
    private static String password=null;
    private static Properties properties=new Properties();

    static {
        try {
//            FileInputStream file=new FileInputStream("db.properties");
            InputStream file=DB.class.getClassLoader().getResourceAsStream("db.properties");
            properties.load(file);
            driverClass=properties.getProperty("jdbc.driver");
            jdbcUrl=properties.getProperty("jdbc.url");
            user=properties.getProperty("jdbc.username");
            password=properties.getProperty("jdbc.password");
            Class.forName(driverClass);
            file.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 建立数据库连接
     * @return Connection
     */
   public static Connection getConnection(){
        Connection conn=null;
       try {
           conn= DriverManager.getConnection(jdbcUrl,user,password);
       } catch (SQLException e) {
           e.printStackTrace();
       }
       return conn;
   }

    /**
     * 关闭数据库连接
     * @param conn 未关闭的连接
     */
   public static void close(Connection conn){
        if(conn!=null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
   }

}
